<template>
    <div class="page-container">
        <!-- Query Form -->
        <div class="search-card">
            <el-form :inline="true" :model="queryParams" class="query-form">
                <el-form-item label="企业名称">
                    <el-input
                        v-model="queryParams.nameFuzzy"
                        placeholder="请输入企业名称"
                        clearable
                        class="custom-input"
                    />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                        clearable
                        class="custom-select"
                        style="width: 160px"
                    >
                        <el-option label="创建未备案" :value="0" />
                        <el-option label="已备案未审核" :value="1" />
                        <el-option label="已退回" :value="2" />
                        <el-option label="正常" :value="3" />
                        <el-option label="倒闭" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="btn-primary-theme" @click="queryEnterprises">
                        <el-icon class="mr-1"><search /></el-icon>查询
                    </el-button>
                    <el-button @click="resetQuery" class="btn-secondary">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- Table Section -->
        <div class="table-card">
            <el-table
                :data="tableData"
                v-loading="loading"
                style="width: 100%"
                class="modern-table"
                :header-cell-style="{
                    background: '#f8fafc',
                    color: '#475569',
                    fontWeight: '700',
                    fontSize: '13px',
                    height: '56px',
                    textAlign: 'center',
                    borderBottom: '1px solid #f1f5f9',
                }"
                :cell-style="{ textAlign: 'center', padding: '8px 0' }"
                :row-style="{ height: '80px' }"
            >
                <!-- Enterprise ID (First Column) -->
                <el-table-column label="企业ID" width="250" align="center">
                    <template #default="{ row }">
                        <span class="cell-text">{{ row.enterpriseId }}</span>
                    </template>
                </el-table-column>

                <!-- Enterprise Name -->
                <el-table-column label="企业名称" min-width="200" align="center">
                    <template #default="{ row }">
                        <span class="cell-primary-text">{{ row.name }}</span>
                    </template>
                </el-table-column>

                <!-- Contact Info -->
                <el-table-column label="联系人" width="180" align="center">
                    <template #default="{ row }">
                        <div class="contact-group">
                            <div class="contact-name">{{ row.contactName || '-' }}</div>
                            <div class="contact-phone">{{ row.phoneNum || '-' }}</div>
                        </div>
                    </template>
                </el-table-column>

                <!-- Status -->
                <el-table-column label="状态" width="160" align="center">
                    <template #default="{ row }">
                        <div class="status-badge" :class="`status-${getStatusType(row.status)}`">
                            <span class="status-dot"></span>
                            {{ getStatusText(row.status) }}
                        </div>
                    </template>
                </el-table-column>

                <!-- Created Time -->
                <el-table-column label="创建时间" width="200" align="center">
                    <template #default="{ row }">
                        <span class="timestamp-text">{{ formatDate(row.createdAt) }}</span>
                    </template>
                </el-table-column>

                <!-- Actions -->
                <el-table-column label="操作" width="200" align="center" fixed="right">
                    <template #default="{ row }">
                        <div class="action-group">
                            <el-button
                                link
                                type="primary"
                                class="action-btn"
                                @click="openViewEnterpriseDialog(row)"
                            >
                                查看
                            </el-button>
                            <div class="divider"></div>
                            <el-button
                                link
                                type="primary"
                                class="action-btn"
                                @click="openEditEnterpriseDialog(row)"
                            >
                                编辑
                            </el-button>
                            <div class="divider"></div>
                            <el-button
                                link
                                type="danger"
                                class="action-btn danger"
                                @click="handleDeleteEnterprise(row)"
                            >
                                删除
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <!-- Pagination -->
            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="queryParams.pageNo"
                    v-model:page-size="queryParams.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                />
            </div>
        </div>

        <!-- Create/Edit Dialog -->
        <el-dialog
            v-model="showCreateEnterpriseDialog"
            :title="isEditMode ? '编辑企业' : '新增企业'"
            width="800px"
            class="custom-dialog"
            align-center
            destroy-on-close
        >
            <div class="dialog-content">
                <el-form
                    ref="enterpriseFormRef"
                    :model="enterpriseForm"
                    label-position="top"
                    class="modern-form"
                >
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="企业名称" required>
                                <el-input 
                                    v-model="enterpriseForm.enterpriseInfo.name" 
                                    placeholder="请输入企业名称" 
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="组织机构代码">
                                <el-input 
                                    v-model="enterpriseForm.enterpriseInfo.orgCode" 
                                    placeholder="请输入代码" 
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                         <el-col :span="12">
                            <el-form-item label="所属地区">
                                <el-cascader
                                    v-model="regionValue"
                                    :options="regionOptions"
                                    :props="{ label: 'name', value: 'code', children: 'children' }"
                                    placeholder="请选择地区"
                                    @change="handleRegionChange"
                                    clearable
                                    class="custom-select"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="所属性质">
                                <el-cascader
                                    v-model="natureValue"
                                    :options="enterpriseTypeOptions"
                                    :props="{ label: 'name', value: 'code', children: 'children' }"
                                    placeholder="请选择性质"
                                    @change="handleNatureChange"
                                    clearable
                                    class="custom-select"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="所属行业">
                                <el-cascader
                                    v-model="industryValue"
                                    :options="enterpriseIndustryOptions"
                                    :props="{ label: 'name', value: 'code', children: 'children' }"
                                    placeholder="请选择行业"
                                    @change="handleIndustryChange"
                                    clearable
                                    class="custom-select"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="联系电话">
                                <el-input 
                                    v-model="enterpriseForm.enterpriseInfo.phoneNum" 
                                    placeholder="请输入电话" 
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                     <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="联系人">
                                <el-input 
                                    v-model="enterpriseForm.enterpriseInfo.contactName" 
                                    placeholder="请输入姓名" 
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="邮箱">
                                <el-input 
                                    v-model="enterpriseForm.enterpriseInfo.email" 
                                    placeholder="请输入邮箱" 
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-form-item label="经营业务详情">
                        <el-input
                            v-model="enterpriseForm.enterpriseInfo.industryDesc"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入详情"
                            class="custom-input"
                        />
                    </el-form-item>

                    <el-form-item label="联系地址">
                        <el-input 
                            v-model="enterpriseForm.enterpriseInfo.address" 
                            placeholder="请输入详细地址" 
                            class="custom-input"
                        />
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <div v-if="isEditMode" class="status-actions">
                        <span class="label">变更状态:</span>
                        <el-button
                            v-for="opt in getAvailableStatusOptions(
                                enterpriseForm.enterpriseInfo.status
                            )"
                            :key="opt.value"
                            :type="getStatusButtonType(opt.value)"
                            size="small"
                            @click="handleStatusChange(opt.value)"
                        >
                            {{ opt.label }}
                        </el-button>
                    </div>
                    <div class="main-actions">
                        <el-button @click="showCreateEnterpriseDialog = false" class="btn-secondary">取消</el-button>
                        <el-button
                            type="primary"
                            class="btn-primary-theme"
                            :loading="actionLoading"
                            @click="isEditMode ? updateEnterprise() : createEnterprise()"
                        >
                            {{ isEditMode ? '保存修改' : '立即创建' }}
                        </el-button>
                    </div>
                </div>
            </template>
        </el-dialog>

        <!-- View Dialog -->
        <el-dialog
            v-model="showViewEnterpriseDialog"
            title="企业详情"
            width="800px"
            class="custom-dialog"
            align-center
        >
            <div class="view-content">
                <el-descriptions :column="2" border class="custom-desc">
                    <el-descriptions-item label="企业名称" :span="2">
                        <span class="view-primary-text">{{
                            viewEnterpriseForm.enterpriseInfo.name
                        }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="企业ID" :span="2">
                        <span class="view-mono-text">{{
                            viewEnterpriseForm.enterpriseInfo.enterpriseId
                        }}</span>
                    </el-descriptions-item>
                    <el-descriptions-item label="状态">
                        <el-tag
                            :type="getStatusType(viewEnterpriseForm.enterpriseInfo.status)"
                            effect="dark"
                            round
                        >
                            {{ getStatusText(viewEnterpriseForm.enterpriseInfo.status) }}
                        </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="组织机构代码">{{
                        viewEnterpriseForm.enterpriseInfo.orgCode || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="联系人">{{
                        viewEnterpriseForm.enterpriseInfo.contactName || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="联系电话">{{
                        viewEnterpriseForm.enterpriseInfo.phoneNum || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="所属地区">{{
                        getRegionName(viewEnterpriseForm.regionValue) || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="所属性质">{{
                        getNatureName(viewEnterpriseForm.natureValue) || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="所属行业" :span="2">{{
                        getIndustryName(viewEnterpriseForm.industryValue) || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="经营业务详情" :span="2">{{
                        viewEnterpriseForm.enterpriseInfo.industryDesc || '-'
                    }}</el-descriptions-item>
                    <el-descriptions-item label="地址" :span="2">{{
                        viewEnterpriseForm.enterpriseInfo.address || '-'
                    }}</el-descriptions-item>
                </el-descriptions>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showViewEnterpriseDialog = false" class="btn-secondary">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- Account Info Dialog -->
        <el-dialog
            v-model="showAccountInfoDialog"
            title="账号创建成功"
            width="400px"
            center
            align-center
        >
            <div class="account-success">
                <el-icon class="success-icon"><Check /></el-icon>
                <h3>企业账号已生成</h3>
                <div class="account-card">
                    <div class="row">
                        <span class="label">用户名</span>
                        <span class="value">{{ createdAccountInfo.username }}</span>
                        <el-icon
                            class="copy-btn"
                            @click="copyToClipboard(createdAccountInfo.username)"
                            ><Collection
                        /></el-icon>
                    </div>
                    <div class="row">
                        <span class="label">密码</span>
                        <span class="value">{{ createdAccountInfo.password }}</span>
                        <el-icon
                            class="copy-btn"
                            @click="copyToClipboard(createdAccountInfo.password)"
                            ><Collection
                        /></el-icon>
                    </div>
                </div>
                <p class="tip">请务必妥善保存此信息</p>
            </div>
            <template #footer>
                <el-button type="primary" @click="closeAccountInfoDialog" style="width: 100%"
                    >知道了</el-button
                >
            </template>
        </el-dialog>

        <!-- Return Reason Dialog -->
        <el-dialog v-model="showReturnDialog" title="退回原因" width="500px">
            <el-form label-position="top">
                <el-form-item label="问题类型">
                    <el-select v-model="returnForm.reasonCategory" style="width: 100%">
                        <el-option
                            v-for="item in returnReasons"
                            :key="item.code"
                            :label="item.name"
                            :value="item.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="具体说明">
                    <el-input v-model="returnForm.detail" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showReturnDialog = false">取消</el-button>
                    <el-button type="primary" @click="submitReturn" :loading="actionLoading"
                        >确认退回</el-button
                    >
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import {
    ElCard,
    ElTable,
    ElTableColumn,
    ElButton,
    ElTag,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElSelect,
    ElOption,
    ElCascader,
    ElPagination,
    ElMessage,
    ElMessageBox,
    ElAlert,
    ElDescriptions,
    ElDescriptionsItem,
    ElIcon,
    ElRow,
    ElCol,
} from 'element-plus';
import {
    WarningFilled,
    OfficeBuilding,
    Collection,
    Location,
    Briefcase,
    Shop,
    User,
    Phone,
    MapLocation,
    Message,
    Check,
    Search,
} from '@element-plus/icons-vue';
import enterpriseApi from '../../api/enterprise.js';
import dictApi from '../../api/dict.js';
import regionData from '../../dict/yunnan_region_code.json';
import enterpriseTypeData from '../../dict/enterprise_type.json';
import enterpriseIndustryData from '../../dict/enterprise_industry.json';

const regionOptions = ref(regionData);
const enterpriseTypeOptions = ref(enterpriseTypeData);
const enterpriseIndustryOptions = ref(enterpriseIndustryData);

const regionValue = ref([]);
const natureValue = ref([]);
const industryValue = ref([]);

const handleRegionChange = (values) => {
    regionValue.value = values;
    enterpriseForm.enterpriseInfo.region =
        values.length > 0 ? values[values.length - 1] : undefined;
};

const handleNatureChange = (values) => {
    natureValue.value = values;
    enterpriseForm.enterpriseInfo.nature =
        values.length > 0 ? values[values.length - 1] : undefined;
};

const handleIndustryChange = (values) => {
    industryValue.value = values;
    enterpriseForm.enterpriseInfo.industry =
        values.length > 0 ? values[values.length - 1] : undefined;
};

const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const actionLoading = ref(false);

const queryParams = ref({
    pageNo: 1,
    pageSize: 10,
    nameFuzzy: '',
    status: undefined,
    region: undefined,
    nature: undefined,
    industry: undefined,
    orderBy: 'created_at desc',
});

const showCreateEnterpriseDialog = ref(false);
const isEditMode = ref(false);
const currentEnterpriseId = ref('');
const showAccountInfoDialog = ref(false);
const showViewEnterpriseDialog = ref(false);
const showReturnDialog = ref(false);
const pendingStatus = ref(null);
const returnReasons = ref([]);
const returnFields = ref([]);
const returnForm = reactive({
    reasonCategory: '',
    reasonFields: [],
    detail: '',
});

const createdAccountInfo = ref({
    enterpriseName: '',
    username: '',
    password: '',
});

const enterpriseForm = reactive({
    enterpriseInfo: {
        name: '',
        orgCode: '',
        region: undefined,
        nature: undefined,
        industry: undefined,
        industryDesc: '',
        contactName: '',
        address: '',
        postalCode: '',
        phoneNum: '',
        faxNum: '',
        email: '',
        status: undefined,
    },
});

const viewEnterpriseForm = reactive({
    enterpriseInfo: {
        enterpriseId: '',
        name: '',
        orgCode: '',
        region: undefined,
        nature: undefined,
        industry: undefined,
        industryDesc: '',
        contactName: '',
        address: '',
        postalCode: '',
        phoneNum: '',
        faxNum: '',
        email: '',
        status: undefined,
        createdAt: '',
        updatedAt: '',
    },
    regionValue: [],
    natureValue: [],
    industryValue: [],
});

const enterpriseFormRef = ref();

const openCreateEnterpriseDialog = () => {
    isEditMode.value = false;
    currentEnterpriseId.value = '';
    if (enterpriseFormRef.value) enterpriseFormRef.value.resetFields();
    Object.keys(enterpriseForm.enterpriseInfo).forEach(
        (key) =>
            (enterpriseForm.enterpriseInfo[key] =
                key === 'status' || key === 'region' || key === 'nature' || key === 'industry'
                    ? undefined
                    : '')
    );
    regionValue.value = [];
    natureValue.value = [];
    industryValue.value = [];
    showCreateEnterpriseDialog.value = true;
};

const findCascaderPath = (targetValue, options, path = []) => {
    if (!targetValue || !options || !Array.isArray(options)) return [];
    for (const option of options) {
        if (!option || option.code === undefined) continue;
        const currentPath = [...path, option.code];
        if (option.code === targetValue) return currentPath;
        if (option.children && Array.isArray(option.children) && option.children.length > 0) {
            const found = findCascaderPath(targetValue, option.children, currentPath);
            if (found && found.length > 0) return found;
        }
    }
    return [];
};

const openViewEnterpriseDialog = async (row) => {
    try {
        const response = await enterpriseApi.getEnterprise(row.enterpriseId);
        if (response && response.code === 200 && response.data) {
            const enterprise = response.data;
            Object.assign(viewEnterpriseForm.enterpriseInfo, enterprise);
            viewEnterpriseForm.enterpriseInfo.status =
                enterprise.status !== undefined ? enterprise.status : 0;

            await nextTick();
            if (enterprise.region)
                viewEnterpriseForm.regionValue = findCascaderPath(
                    enterprise.region,
                    regionOptions.value
                );
            if (enterprise.nature)
                viewEnterpriseForm.natureValue = findCascaderPath(
                    enterprise.nature,
                    enterpriseTypeOptions.value
                );
            if (enterprise.industry)
                viewEnterpriseForm.industryValue = findCascaderPath(
                    enterprise.industry,
                    enterpriseIndustryOptions.value
                );

            showViewEnterpriseDialog.value = true;
        } else {
            ElMessage.error('加载企业信息失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error('加载企业信息失败');
    }
};

const openEditEnterpriseDialog = async (row) => {
    isEditMode.value = true;
    currentEnterpriseId.value = row.enterpriseId;
    if (enterpriseFormRef.value) enterpriseFormRef.value.resetFields();
    regionValue.value = [];
    natureValue.value = [];
    industryValue.value = [];

    try {
        const response = await enterpriseApi.getEnterprise(row.enterpriseId);
        if (response && response.code === 200 && response.data) {
            const enterprise = response.data;
            Object.assign(enterpriseForm.enterpriseInfo, enterprise);
            enterpriseForm.enterpriseInfo.status =
                enterprise.status !== undefined ? enterprise.status : 0;

            showCreateEnterpriseDialog.value = true;
            await nextTick();

            if (enterprise.region)
                regionValue.value = findCascaderPath(enterprise.region, regionOptions.value) || [];
            if (enterprise.nature)
                natureValue.value =
                    findCascaderPath(enterprise.nature, enterpriseTypeOptions.value) || [];
            if (enterprise.industry)
                industryValue.value =
                    findCascaderPath(enterprise.industry, enterpriseIndustryOptions.value) || [];

            // Ensure form data sync
            enterpriseForm.enterpriseInfo.region = enterprise.region;
            enterpriseForm.enterpriseInfo.nature = enterprise.nature;
            enterpriseForm.enterpriseInfo.industry = enterprise.industry;
        } else {
            ElMessage.error('加载企业信息失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error('加载企业信息失败');
    }
};

const createEnterprise = async () => {
    if (!enterpriseFormRef.value) return;
    try {
        if (!enterpriseForm.enterpriseInfo.name?.trim()) {
            ElMessage.error('请输入企业名称');
            return;
        }
        actionLoading.value = true;
        const response = await enterpriseApi.createEnterprise({
            enterpriseInfo: { ...enterpriseForm.enterpriseInfo },
        });
        if (response && response.code === 200) {
            if (response.data) {
                createdAccountInfo.value = {
                    enterpriseName: enterpriseForm.enterpriseInfo.name || '',
                    username: response.data.username || '',
                    password: response.data.password || '',
                };
            }
            showCreateEnterpriseDialog.value = false;
            showAccountInfoDialog.value = true;
            await loadEnterprises();
        } else {
            ElMessage.error(response?.info || '创建企业失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error(error?.response?.data?.message || error?.message || '创建企业失败');
    } finally {
        actionLoading.value = false;
    }
};

const submitReturn = async () => {
    if (!returnForm.reasonCategory) {
        ElMessage.error('请选择主要问题类型');
        return;
    }
    try {
        actionLoading.value = true;
        const response = await enterpriseApi.changeEnterpriseStatus(currentEnterpriseId.value, 2, {
            reasonCategory: returnForm.reasonCategory,
            reasonFields: returnForm.reasonFields,
            detail: returnForm.detail?.trim() || '',
        });
        if (response && response.code === 200) {
            ElMessage.success('退回操作成功');
            enterpriseForm.enterpriseInfo.status = 2;
            showReturnDialog.value = false;
            showCreateEnterpriseDialog.value = false;
            await loadEnterprises();
        } else {
            ElMessage.error(response?.info || '退回操作失败');
        }
    } catch (e) {
        ElMessage.error('退回操作失败');
    } finally {
        actionLoading.value = false;
    }
};

const updateEnterprise = async () => {
    if (!enterpriseFormRef.value) return;
    try {
        if (!enterpriseForm.enterpriseInfo.name?.trim()) {
            ElMessage.error('请输入企业名称');
            return;
        }
        actionLoading.value = true;
        const response = await enterpriseApi.updateEnterprise(
            currentEnterpriseId.value,
            enterpriseForm.enterpriseInfo
        );
        if (response && response.code === 200) {
            ElMessage.success('更新成功');
            showCreateEnterpriseDialog.value = false;
            await loadEnterprises();
        } else {
            ElMessage.error(response?.info || '更新失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error(error?.message || '更新失败');
    } finally {
        actionLoading.value = false;
    }
};

const handleDeleteEnterprise = async (row) => {
    try {
        await ElMessageBox.confirm(`确定要删除企业「${row.name}」吗？`, '删除确认', {
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-danger-theme',
            cancelButtonClass: 'btn-secondary',
        });
        actionLoading.value = true;
        const response = await enterpriseApi.deleteEnterprise(row.enterpriseId);
        if (response && response.code === 200) {
            ElMessage.success('删除成功');
            await loadEnterprises();
        } else {
            ElMessage.error(response?.info || '删除失败');
        }
    } catch (error) {
        if (error !== 'cancel') {
            console.error(error);
            ElMessage.error('删除失败');
        }
    } finally {
        actionLoading.value = false;
    }
};

const loadEnterprises = async () => {
    try {
        loading.value = true;
        const response = await enterpriseApi.loadAllEnterprise(queryParams.value);
        if (response && response.code === 200) {
            tableData.value = response.data?.list || [];
            total.value = (response.data && (response.data.totalCount ?? response.data.total)) || 0;
        } else {
            ElMessage.error(response?.info || '加载列表失败');
        }
    } catch (error) {
        console.error(error);
        ElMessage.error('加载列表失败');
    } finally {
        loading.value = false;
    }
};

const queryEnterprises = () => {
    queryParams.value.pageNo = 1;
    loadEnterprises();
};

const resetQuery = () => {
    queryParams.value = {
        pageNo: 1,
        pageSize: 10,
        nameFuzzy: '',
        status: undefined,
        region: undefined,
        nature: undefined,
        industry: undefined,
        orderBy: 'created_at desc',
    };
    loadEnterprises();
};

const handleSizeChange = (size) => {
    queryParams.value.pageSize = size;
    loadEnterprises();
};

const handleCurrentChange = (current) => {
    queryParams.value.pageNo = current;
    loadEnterprises();
};

const statusOptions = [
    { value: 0, label: '创建未备案' },
    { value: 1, label: '已备案未审核' },
    { value: 2, label: '已退回' },
    { value: 3, label: '正常' },
    { value: 4, label: '倒闭' },
];

const getAvailableStatusOptions = (currentStatus) => {
    // 停用/倒闭状态允许恢复到任意其它状态
    if (currentStatus === 4) return statusOptions.filter((i) => i.value !== 4);
    if (currentStatus === 1) return statusOptions.filter((i) => i.value === 2 || i.value === 3);
    if (currentStatus === 2) return statusOptions.filter((i) => i.value === 1 || i.value === 4);
    if (currentStatus === 3) return statusOptions.filter((i) => i.value === 4);
    return [];
};

const getStatusText = (status) => statusOptions.find((o) => o.value === status)?.label || '未知';

const getStatusType = (status) => {
    const map = { 0: 'info', 1: 'warning', 2: 'danger', 3: 'success', 4: 'danger' };
    return map[status] || 'info';
};

const getStatusButtonType = (status) => getStatusType(status);

const getRegionName = (path) => {
    if (!path || path.length === 0) return '';
    let current = regionOptions.value;
    let names = [];
    for (let code of path) {
        const item = current.find((o) => o.code === code);
        if (item) {
            names.push(item.name);
            current = item.children || [];
        } else break;
    }
    return names.join(' / ');
};

const getNatureName = (path) => {
    if (!path || path.length === 0) return '';
    let current = enterpriseTypeOptions.value;
    let names = [];
    for (let code of path) {
        const item = current.find((o) => o.code === code);
        if (item) {
            names.push(item.name);
            current = item.children || [];
        } else break;
    }
    return names.join(' / ');
};

const getIndustryName = (path) => {
    if (!path || path.length === 0) return '';
    let current = enterpriseIndustryOptions.value;
    let names = [];
    for (let code of path) {
        const item = current.find((o) => o.code === code);
        if (item) {
            names.push(item.name);
            current = item.children || [];
        } else break;
    }
    return names.join(' / ');
};

const handleStatusChange = async (newStatus) => {
    try {
        await ElMessageBox.confirm(`确定修改状态为「${getStatusText(newStatus)}」吗？`, '确认', {
            type: 'warning',
            customClass: 'custom-message-box',
            confirmButtonClass: 'btn-primary-theme',
            cancelButtonClass: 'btn-secondary',
        });
        if (newStatus === 2) {
            pendingStatus.value = newStatus;
            returnForm.reasonCategory = '';
            returnForm.reasonFields = [];
            returnForm.detail = '';
            try {
                const [rs, fs] = await Promise.all([
                    dictApi.getReturnReasons(),
                    dictApi.getReturnFields(),
                ]);
                returnReasons.value = rs?.data || [];
                returnFields.value = fs?.data || [];
            } catch (e) {}
            showReturnDialog.value = true;
            return;
        }
        actionLoading.value = true;
        const response = await enterpriseApi.changeEnterpriseStatus(
            currentEnterpriseId.value,
            newStatus
        );
        if (response && response.code === 200) {
            ElMessage.success('修改成功');
            enterpriseForm.enterpriseInfo.status = newStatus;
            showCreateEnterpriseDialog.value = false;
            await loadEnterprises();
        } else {
            ElMessage.error(response?.info || '修改失败');
        }
    } catch (error) {
        if (error !== 'cancel') ElMessage.error('修改失败');
    } finally {
        actionLoading.value = false;
    }
};

const formatDate = (date) => {
    if (!date) return '-';
    const d = new Date(date);
    return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const copyToClipboard = async (text) => {
    try {
        await navigator.clipboard.writeText(text);
        ElMessage.success('已复制');
    } catch (e) {
        ElMessage.error('复制失败');
    }
};

const closeAccountInfoDialog = () => (showAccountInfoDialog.value = false);

onMounted(() => loadEnterprises());
</script>

<style scoped lang="scss">
.page-container {
    padding: 24px 40px;
    // background-color: #f8fafc;
    min-height: 100vh;
    font-family: 'Inter', sans-serif;
}

.search-card {
    background: white;
    padding: 20px 24px;
    border-radius: 16px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    margin-bottom: 24px;
    border: 1px solid #f1f5f9;

    .query-form {
        margin-bottom: 0;
        .el-form-item {
            margin-bottom: 0;
            margin-right: 24px;
        }
    }
}

.table-card {
    background: white;
    border-radius: 24px;
    box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.02),
        0 10px 15px -3px rgba(0, 0, 0, 0.04);
    padding: 8px;
    border: 1px solid #f1f5f9;
}

.modern-table {
    border-radius: 16px;
    overflow: hidden;
}

/* --- Cell Styling --- */
.cell-text {
    font-size: 14px;
    color: #0f172a;
}

.cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
}

.contact-group {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.contact-name {
    font-size: 14px;
    color: #1e293b;
    font-weight: 500;
}

.contact-phone {
    font-size: 12px;
    color: #64748b;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    border-radius: 99px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.5;
}

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-success {
    background: #ecfdf5;
    color: #059669;
    .status-dot {
        background: #10b981;
    }
}
.status-warning {
    background: #fff7ed;
    color: #ea580c;
    .status-dot {
        background: #f97316;
    }
}
.status-danger {
    background: #fef2f2;
    color: #dc2626;
    .status-dot {
        background: #ef4444;
    }
}
.status-info {
    background: #f1f5f9;
    color: #64748b;
    .status-dot {
        background: #94a3b8;
    }
}

.timestamp-text {
    color: #64748b;
    font-size: 13px;
    font-variant-numeric: tabular-nums;
}

/* Actions */
.action-group {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

.divider {
    width: 1px;
    height: 14px;
    background: #e2e8f0;
}

.action-btn {
    font-weight: 600;
    padding: 4px 8px;
    height: auto;

    &.danger {
        color: #ef4444;
        &:hover {
            color: #dc2626;
        }
    }
}

.pagination-wrapper {
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
}

/* --- Buttons --- */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
    border: none;
    padding: 10px 24px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
    transition: all 0.2s;

    &:hover {
        transform: translateY(-1px);
        box-shadow: 0 8px 20px rgba(79, 70, 229, 0.3);
    }
}

.btn-secondary {
    padding: 10px 24px;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    color: #475569;

    &:hover {
        background: #f8fafc;
        color: #1e293b;
        border-color: #cbd5e1;
    }
}

/* --- Form Inputs --- */
.custom-input,
.custom-select {
    :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        padding: 6px 12px;

        &.is-focus {
            box-shadow: 0 0 0 2px #818cf8 inset;
        }
    }
}

/* --- Dialog Customization --- */
:deep(.custom-dialog) {
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);

    .el-dialog__header {
        margin: 0;
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        
        .el-dialog__title {
            font-weight: 700;
            font-size: 18px;
            color: #0f172a;
        }
    }

    .el-dialog__body {
        padding: 32px;
    }

    .el-dialog__footer {
        padding: 20px 24px;
        border-top: 1px solid #f1f5f9;
        background-color: #f8fafc;
    }
}

/* --- View Dialog Typography --- */
.view-primary-text {
    font-size: 16px;
    font-weight: 600;
    color: #0f172a;
}

.view-mono-text {
    font-family: 'JetBrains Mono', monospace;
    font-size: 13px;
    color: #64748b;
    background: #f1f5f9;
    padding: 2px 8px;
    border-radius: 4px;
}

/* --- Dialog Footer --- */
.dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 20px; /* More spacing from content */
    margin-top: 0;
}

.status-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    background: #f8fafc;
    padding: 6px 16px;
    border-radius: 8px;
    border: 1px solid #f1f5f9;

    .label {
        font-size: 13px;
        font-weight: 600;
        color: #64748b;
    }
}

.main-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-left: auto;
}

/* --- Account Success --- */
.account-success {
    text-align: center;
    padding: 20px 0;

    .success-icon {
        font-size: 48px;
        color: #10b981;
        margin-bottom: 16px;
    }
    h3 {
        margin: 0 0 24px 0;
        color: #1e293b;
    }

    .account-card {
        background: #f8fafc;
        border-radius: 12px;
        padding: 16px;
        border: 1px solid #f1f5f9;

        .row {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            &:last-child {
                margin-bottom: 0;
            }

            .label {
                width: 60px;
                text-align: left;
                color: #94a3b8;
                font-size: 13px;
            }
            .value {
                flex: 1;
                text-align: right;
                font-family: monospace;
                font-size: 15px;
                color: #334155;
                font-weight: 600;
            }
            .copy-btn {
                margin-left: 12px;
                cursor: pointer;
                color: #4f46e5;
                &:hover {
                    color: #4338ca;
                }
            }
        }
    }
    .tip {
        margin-top: 16px;
        color: #ef4444;
        font-size: 12px;
    }
}

/* --- Create Dialog Form --- */
.modern-form {
    .form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;

        .grid-col-2 {
            grid-column: span 2;
        }
    }

    :deep(.el-form-item__label) {
        font-weight: 600;
        color: #475569;
        margin-bottom: 8px;
    }
}
</style>

<style lang="scss">
/* Global styles for ElMessageBox */
.custom-message-box {
    border-radius: 16px !important;
    overflow: hidden;
    border: none !important;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25) !important;
    padding-bottom: 20px !important;

    .el-message-box__header {
        padding: 20px 24px;
        border-bottom: 1px solid #f1f5f9;
        
        .el-message-box__title {
            font-weight: 700;
            color: #0f172a;
        }
    }

    .el-message-box__content {
        padding: 24px;
        color: #334155;
        font-size: 15px;
    }

    .el-message-box__btns {
        padding: 0 24px 0 0;
        
        .el-button {
            border-radius: 8px;
            font-weight: 600;
            padding: 10px 20px;
            height: auto;
        }

        .btn-primary-theme {
            background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%);
            border: none;
            color: white;
            
            &:hover {
                transform: translateY(-1px);
                box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
            }
        }

        .btn-danger-theme {
            background: #ef4444;
            border: none;
            color: white;
            
            &:hover {
                background: #dc2626;
            }
        }

        .btn-secondary {
            background: #fff;
            border: 1px solid #e2e8f0;
            color: #475569;
            
            &:hover {
                background: #f8fafc;
                color: #1e293b;
            }
        }
    }
}
</style>
